package com.module.my.view

import android.app.Activity
import android.content.Intent
import android.view.ViewGroup
import com.module.app.base.BaseListActivity
import com.module.app.widget.gallery.GalleryPop
import com.module.base.base.adapter.BaseAdapter
import com.module.base.base.adapter.BaseNewAdapter
import com.module.base.base.adapter.BaseNewAdapter.OnItemOtherClickListener
import com.module.base.utils.CollectionUtil
import com.module.base.utils.ToastUtils
import com.module.base.utils.imagepicker.CommonImagePickerUtils
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.config.PictureMimeType
import com.module.frame.ext.observe
import com.module.my.R
import com.module.my.adapter.holder.SkinHolder
import com.module.my.databinding.MyActivitySkinBinding
import com.module.my.model.SkinViewModel
import com.module.my.utils.startVip
import com.module.skin.SkinUtils
import com.yalantis.ucrop.UCrop

class SkinActivity : BaseListActivity<SkinViewModel, MyActivitySkinBinding, BaseAdapter>() {

    private var position = -1
    private var oldPosition = -1

    override fun bingViewModel() {
        mDatabind.vm = mViewModel
        mViewModel.context = getContext()
        mViewModel.activity = getActivity()
    }

    override fun createAdapter(): BaseAdapter {
        return object : BaseAdapter() {
            override fun onCreateDefaultViewHolder(
                parent: ViewGroup,
                viewType: Int
            ): SkinHolder {
                return SkinHolder(parent)
            }
        }
    }

    override fun initView() {
        super.initView()
        setMyTitle(R.string.my_title_skin)
    }

    override fun initListener() {
        super.initListener()
        observe(mViewModel.positionFlow) {
            setPosition(it)
        }
        observe(mViewModel.cropSucFlow) {
            cropSuc(it)
        }
        observe(mViewModel.selectSkinFlow) {
            selectSkin(it.holder, it.bean)
        }
        adapter.setOnItemOtherClickListener(OnItemOtherClickListener<SkinHolder, com.module.app.bean.SkinBean> { holder, view, bean ->
            if (R.id.tv_preview === view.id) {
                if (!CollectionUtil.isEmptyOrNull(bean.preview)) {
                    GalleryPop.show(getContext(), bean.preview)
                }
            }
        })
        adapter.setOnItemClickListener(BaseNewAdapter.OnItemClickListener<SkinHolder?, com.module.app.bean.SkinBean> { holder, bean ->
            if (bean.isVip && !com.module.app.utils.UserUtils.isLogin(true)) {
                return@OnItemClickListener
            }
            if (bean.isVip && !com.module.app.utils.UserUtils.isVip()) {
                //VIP专享，但是不是vip
                com.module.app.pop.CommonPop.Builder(getContext())
                    .setContent(R.string.my_skin_vip_content)
                    .setCancelButton(R.string.cancel)
                    .setConfirmButton(R.string.buy_vip)
                    .setOnConfirmListener { getContext().startVip() }
                    .show()
                return@OnItemClickListener
            }

            //是否是自动设置夜间了，，当自动设置夜间了，则主题选择失效不能选择
            if (com.module.app.utils.AutoSkinNightUtils.isNight()) {
                com.module.app.pop.CommonPop.Builder(getContext())
                    .setContent(R.string.my_skin_night_select_skin)
                    .setCancelButton(R.string.cancel)
                    .setConfirmButton(R.string.go_to)
                    .setOnConfirmListener {
                        getActivity().startActivity(
                            Intent(
                                getActivity(),
                                AutoSkinNightActivity::class.java
                            )
                        )
                    }
                    .show()
                return@OnItemClickListener
            }
            if (com.module.app.utils.MySkinUtils.isUpdate(bean)) {
                //有新版本
                com.module.app.pop.CommonPop.Builder(getContext())
                    .setContent(R.string.my_skin_update)
                    .setCancelButton(R.string.cancel)
                    .setConfirmButton(R.string.download)
                    .setOnConfirmListener { mViewModel.downloadSkin(holder, bean) }
                    .show()
                return@OnItemClickListener
            }
            if (bean.isSelect) {
                //已经选中无法取消
                return@OnItemClickListener
            }
            if (com.module.app.utils.MySkinUtils.isDownload(bean)) {
                //该主题需要下载
                com.module.app.pop.CommonPop.Builder(getContext())
                    .setContent(R.string.my_skin_download)
                    .setCancelButton(R.string.cancel)
                    .setConfirmButton(R.string.download)
                    .setOnConfirmListener { mViewModel.downloadSkin(holder, bean) }
                    .show()
            } else {
                selectSkin(holder, bean)
            }
        })
    }

    override fun initData() {
        super.initData()
        reload()
    }

    /**
     * 选中皮肤
     */
    fun selectSkin(holder: SkinHolder, bean: com.module.app.bean.SkinBean) {
        adapter.notifyItemChanged(holder.curPosition)
        position = holder.curPosition
        if (bean.isBg) {
            XXPermissions.with(getContext())
                .permission(Permission.READ_EXTERNAL_STORAGE)
                .permission(Permission.WRITE_EXTERNAL_STORAGE)
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: List<String>, all: Boolean) {
                        if (all) {
                            CommonImagePickerUtils.show(
                                getContext() as Activity?,
                                PictureMimeType.ofImage(),
                                1
                            )
                        }
                    }

                    override fun onDenied(permissions: List<String>, never: Boolean) {
                        if (never) {
                            ToastUtils.showLong(R.string.permissions_write_read_never_reject)
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(getContext(), permissions)
                        } else {
                            ToastUtils.showShort(R.string.permissions_reject)
                        }
                    }
                })
        } else {
            cancelOldSelect()
            com.module.app.utils.MySkinUtils.saveCurSkinBean(bean)
            bean.isSelect = true
            holder.setSelect()
            //设置皮肤
            if (bean.isSD) {
                com.module.app.utils.MySkinUtils.addSDSkin(bean)
                SkinUtils.setSDSkin(bean.skinName)
            } else {
                SkinUtils.setSkin(bean.skinName)
            }
        }
    }

    /**
     * 取消旧的选中
     */
    private fun cancelOldSelect() {
        //取消原来
        if (adapter.data.size > oldPosition && oldPosition != -1) {
            if (adapter.data[oldPosition] is com.module.app.bean.SkinBean) {
                (adapter.data[oldPosition] as com.module.app.bean.SkinBean).isSelect = false
            }
            adapter.notifyItemChanged(oldPosition)
            oldPosition = position
        }
    }


    override fun onListLoadPage(isPull: Boolean, isRefresh: Boolean, page_no: Int, page_size: Int) {
        mViewModel.getData()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (CommonImagePickerUtils.onActivityResult(requestCode, resultCode)) {
            // 系统相册结果回调
            onPictureResult(CommonImagePickerUtils.getList(data))
        } else if (requestCode == UCrop.REQUEST_CROP) {
            //裁剪
            var cutPath: String = try {
                val resultUri = UCrop.getOutput(data!!)
                resultUri?.path.toString()
            } catch (e: Exception) {
                mViewModel.getBgUrl() ?: ""
            }
            cropSuc(cutPath)
        }
    }


    /**
     * 相册回调
     */
    private fun onPictureResult(result: List<Any>) {
        mViewModel.crop(result)
    }

    /**
     * 裁剪完成，设置背景主题
     */
    fun cropSuc(path: String?) {
        if (adapter.data.size <= position || position == -1) {
            return
        }
        val mObject: Any? = adapter.data[position]
        var skinBean: com.module.app.bean.SkinBean? = null
        if (mObject is com.module.app.bean.SkinBean) {
            skinBean = mObject
        }
        if (skinBean == null) {
            return
        }
        cancelOldSelect()
        skinBean.bgUrl = path
        com.module.app.utils.MySkinUtils.saveCurSkinBean(skinBean)
        skinBean.isSelect = true
        adapter.notifyItemChanged(position)
        //设置皮肤
        if (skinBean.isSD) {
            com.module.app.utils.MySkinUtils.addSDSkin(skinBean)
            SkinUtils.setSDSkin(skinBean.skinName)
        } else {
            SkinUtils.setSkin(skinBean.skinName)
        }
    }

    fun setPosition(position: Int) {
        this.position = position
        oldPosition = position
    }

}